<script setup lang="ts">
import {
  NButton,
  NSpace,
  NDataTable,
  NInput,
  type DataTableColumns,
  NPagination,
  NForm,
  NFormItem,
  NModal,
  NSpin,
  NSelect,
  NScrollbar,
  useMessage,
  NDatePicker,
  NIcon,
  type FormInst
} from 'naive-ui'
import { h, onMounted, reactive, ref } from 'vue'
import ApproveProcess from '@/components/Approve/approveProcess.vue'
import { sendRequest } from '@/utils/api'
import { useTagStore } from '@/stores/layout'
import type { HttpResponsePagination, HttpResponse } from '@/utils/http'
import type { InterpreterModel } from '@/api/interpreter'
import { ApprovalFilled } from '@vicons/material'
import { ErrorRound } from '@vicons/material'
import { CloseFilled } from '@vicons/material'
import { useRouter, useRoute } from 'vue-router'
import FixedAction from '@/components/FixedAction.vue'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import VBackImg from '@/assets/images/back.png'
import dayjs from 'dayjs'
const tags = useTagStore().tags
const message = useMessage()
const router = useRouter()
const route = useRoute()
const mode = ref<string>('add')
const spinShow = ref(false)
const formValue = reactive<Record<string, any>>({
  date: null, // 使用时间
  userInfo: null, // 用途
  entityId: null,
  draft: null,
  list: [{ collectibleName: null, assessNumber: null, remark: null, dataRequirements: null }]
})
const contentVisible = ref(false)
const addCollect = () => {
  formValue.list = [
    ...formValue.list,
    { collectibleName: null, assessNumber: null, remark: null, dataRequirements: null }
  ]
  message.success('添加成功')
}
const deleteCollect = (index: number) => {
  const newList = [...formValue.list]
  newList.splice(index, 1)
  formValue.list = newList
  message.success('删除成功')
}
/** 返回 */
const goBack = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)
  tags.splice(index, 1)
  if (tags.length == 0) {
    router.push({ path: '/OA/Workbench/UserDesktop' })
  } else history.back()
}
const contentContent = ref()
const confirm = (status: number) => {
  contentContent.value = status ? '您确定要保存草稿吗？' : ' 您确定要提交申请吗？'
  formRef.value?.validate(async (err) => {
    console.log(err)
    if (err) return
    contentVisible.value = true
    formValue.draft = status
  })
}
const loading = ref(false)
/** 保存 */
const submit = async () => {
  loading.value = true
  const params = {
    startUsageTime: formValue.date ? dayjs(formValue.date[0]).format('YYYY-MM-DD') : null,
    endUsageTime: formValue.date ? dayjs(formValue.date[1]).format('YYYY-MM-DD') : null,
    purpose: formValue.userInfo,
    digitalCollectiblesList: formValue.list,
    entityId: formValue.entityId,
    draftFlag: formValue.draft
  }
  let api = 'update'
  if (mode.value === 'add' || (mode.value === 'edit' && route.query.flat)) {
    api = 'save'
  }
  const [error, res] = await sendRequest<HttpResponse<any>>({
    module: 'digitalCollect',
    api,
    override: {
      data:
        api === 'save'
          ? params
          : {
              ...params,
              id: route.query.id
            }
    }
  })
  if (error) {
    loading.value = false
    throw error
  }
  if (res.code !== 0) {
    loading.value = false
    throw new Error(res.msg)
  }
  message.success(res.data || '保存成功')
  loading.value = false
  contentVisible.value = false
  goBack()
}
/** 获取工作流 */
const hint = ref()
const workFlowList = ref(' ')
const getWorkFlow = async () => {
  const [error, res] = await sendRequest({
    module: 'receiveOrDispatch',
    api: 'workFlow',
    override: {
      params: {
        functionCode: 'A0576'
      }
    }
  })
  if (error) return
  if (res.code !== 0) return
  const { entityId } = res.data
  formValue.entityId = res.data.entityId
  hint.value = res.data.remark
  workFlowList.value = res.data.workFlowList?.length
    ? res.data.workFlowList?.map((it: any) => it).join(' → ')
    : null
}
getWorkFlow()
const getCollectDetail = async (id: string) => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'digitalCollect',
    api: 'info',
    uri: {
      id
    }
  })
  if (error) throw error
  if (res.code !== 0) throw new Error(res.msg)
  const { startUsageTime, endUsageTime, purpose, digitalCollectiblesList } = res.data
  formValue.date = [dayjs(startUsageTime).valueOf(), dayjs(endUsageTime).valueOf()]
  formValue.userInfo = purpose
  formValue.list = digitalCollectiblesList || []
}
onMounted(() => {
  if (route.query.id) {
    mode.value = 'edit'
    getCollectDetail(String(route.query.id))
  }
})
const formRef = ref<FormInst | null>(null)
const rules: any = {
  userInfo: {
    required: true,
    message: '请输入用途',
    trigger: ['blur', 'input', 'change']
  }
}
</script>

<template>
  <div class="main">
    <div class="topTitle">{{ mode === 'add' ? '数字藏品提用' : '数字藏品编辑' }}</div>
    <div class="form_content">
      <NScrollbar>
        <NSpin :show="spinShow">
          <div class="content">
            <div
              class="progressHint"
              v-if="hint"
            >
              <NIcon
                size="20"
                class="iconStyle"
              >
                <ErrorRound />
              </NIcon>
              <div
                style="white-space: pre-wrap"
                v-html="hint"
              ></div>
            </div>
            <div class="progress">
              <div style="display: flex; margin-right: 10rem">
                <NIcon
                  :size="20"
                  class="iconStyle"
                >
                  <ApprovalFilled />
                </NIcon>
                <span>审批流程</span>
              </div>
              <span
                style="font-size: 18rem; flex: 1"
                :style="{ color: !workFlowList ? 'red' : '#79bb92' }"
              >
                {{ workFlowList ? workFlowList : '暂无配置流程，请联系管理员进行配置' }}
              </span>
            </div>

            <div class="content_cen">
              <NForm
                ref="formRef"
                require-mark-placement="left"
                label-placement="left"
                :rules="rules"
                :label-width="110"
                :model="formValue"
                label-align="right"
                style="width: 390rem"
              >
                <NFormItem
                  label="使用时间:"
                  path="date"
                >
                  <NDatePicker
                    v-model:value="formValue.date"
                    type="daterange"
                    clearable
                    class="commonWidth"
                  />
                </NFormItem>
                <NFormItem
                  label="用途:"
                  path="userInfo"
                >
                  <NInput
                    type="textarea"
                    placeholder="请输入用途"
                    clearable
                    v-model:value="formValue.userInfo"
                    class="commonWidth"
                  />
                </NFormItem>
                <div class="line"></div>
                <div class="center_title">藏品数据(此单中数据要求填写浏览/高清/原图)</div>
                <div
                  v-for="(item, index) in formValue.list"
                  :key="index"
                  class="collect_box"
                >
                  <NFormItem
                    label="藏品名称:"
                    :path="`list[${index}].collectibleName`"
                    :rule="{
                      required: true,
                      message: '请输入藏品名称',
                      trigger: ['input', 'blur', 'change']
                    }"
                  >
                    <NInput
                      placeholder="请输入藏品名称"
                      clearable
                      v-model:value="item.collectibleName"
                      class="commonWidth"
                    />
                  </NFormItem>
                  <NFormItem label="藏品条码号:">
                    <NInput
                      placeholder="请输入藏品条码号"
                      clearable
                      v-model:value="item.assessNumber"
                      class="commonWidth"
                    />
                  </NFormItem>
                  <NFormItem label="数据要求:">
                    <NInput
                      placeholder="请输入数据要求"
                      clearable
                      v-model:value="item.dataRequirements"
                      class="commonWidth"
                    />
                  </NFormItem>
                  <NFormItem label="备注:">
                    <NInput
                      type="textarea"
                      placeholder="请输入备注"
                      clearable
                      v-model:value="item.remark"
                      class="commonWidth"
                    />
                  </NFormItem>
                  <div
                    class="line"
                    v-if="index !== formValue.list.length - 1"
                  ></div>
                  <div class="delete_btn">
                    <NButton
                      circle
                      type="error"
                      size="tiny"
                      @click="deleteCollect(index)"
                      style="margin-top: 5rem"
                    >
                      <div style="height: 34rem; line-height: 34rem">—</div>
                    </NButton>
                  </div>
                </div>
                <div style="display: flex; justify-content: center">
                  <NButton
                    @click="addCollect"
                    type="primary"
                  >
                    添加藏品
                  </NButton>
                </div>
              </NForm>
            </div>
          </div>
        </NSpin>
      </NScrollbar>
    </div>
  </div>
  <FixedAction>
    <div style="display: flex">
      <NSpace
        justify="start"
        style="flex: 0 0 42%"
      >
        <NButton
          style="width: 78px; color: #5fb17f"
          ghost
          @click="goBack"
        >
          <template #icon>
            <img
              :src="VBackImg"
              style="width: 25rem; height: 25rem"
            />
          </template>
          返回
        </NButton>
      </NSpace>

      <NSpace justify="center">
        <NButton
          type="primary"
          style="background-color: #5faab1"
          @click="confirm(1)"
        >
          保存草稿
        </NButton>
        <NButton
          type="primary"
          @click="confirm(0)"
        >
          提交申请
        </NButton>
      </NSpace>
    </div>
  </FixedAction>
  <NModal
    :auto-focus="false"
    v-model:show="contentVisible"
    @close="contentVisible = false"
  >
    <VDialogContent
      @close="contentVisible = false"
      @submit="submit"
      title="保存提示"
      :loading="loading"
    >
      <div style="width: 300px; height: 100px; text-align: center; line-height: 100px">
        {{ contentContent }}
      </div>
    </VDialogContent>
  </NModal>
</template>

<style scoped lang="scss">
.commonWidthB {
  width: 105rem;
}

@mixin CommonFont {
  font-size: 16rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
}

.commonWidth {
  width: 280rem;
}

.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .topTitle {
    width: 100%;
    border-bottom: 1px solid #fff;
    padding: 15rem 20rem;
    margin-bottom: 20rem;
    @include CommonFont;
  }

  .form_content {
    width: 100%;
    height: 100%;
    padding: 0 20rem 0rem;

    .content {
      display: flex;
      flex-wrap: wrap;
      padding: 20rem 0 180rem;
      background-color: #ebeceb;

      .scope {
        display: flex;
        flex-wrap: wrap;
        width: 100%;

        .userBox {
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: 100%;
          min-height: 40rem;
          background-color: #fff;
          border-radius: 4rem;
          padding: 5px 10rem;
          margin-bottom: 10rem;
        }
      }
    }
  }
}

.content_cen {
  display: flex;
  flex-direction: column;
  margin-left: 35%;
}

.iconStyle {
  margin-right: 5rem;
  color: #5fb17f;
}

.progress {
  display: flex;
  align-items: center;
  min-width: 390rem;
  max-width: 800rem;
  min-height: 50rem;
  background-color: #d5e2d8;
  border-radius: 5rem;
  margin-bottom: 10px;
  padding: 5px 15px;
  margin-left: 35%;
}

.progressHint {
  display: flex;
  min-width: 350rem;
  max-width: 800rem;
  padding: 5px 15px;
  margin-left: 35%;
}

.content::-webkit-scrollbar {
  display: none;
}

:deep(.n-spin-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-spin-content) {
  width: 100%;
  height: 100%;
}

.line {
  width: 100%;
  height: 1px;
  background-color: #cbcbcb;
  margin: 20px 0;
}
.collect_box {
  width: 400rem;
  position: relative;
  .delete_btn {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    right: -60px;
  }
}
</style>
